package com.ly.demo.classdemo;

/**
 * @author liuyang
 * @des instanceof左侧的引用类型变量所引入对象的实际类型是其右侧给出的类型或是其子类类型时，整个表达式的结果为true
 * @Version 1.0
 * @Date: 05/08/2021 10:20
 */

public class InstanceDemo2 {
    //判断对象类型
    public static void typeof(Object obj) {
        if (obj instanceof Derive) {
            Derive der = (Derive)obj;
            der.print();
        } else if (obj instanceof Derive1) {
            Derive1 der1 = (Derive1)obj;
            der1.print();
        }
    }

    public static void main(String[] args) {
        IBase b1 = new Derive(4);//父类引用指向子类对象
        IBase b2 = new Derive1(4, 5);
        System.out.print("b1 is ");
        //调用typeof()判断b1对象类型
        typeof(b1);
        System.out.print("b2 is ");
        //调用typeof()判断b2对象类型
        typeof(b2);
    }
}

//定义Interface接口IBase
interface IBase {
    public void print();
}

//定义Derive类实现IBase接口
class Derive implements IBase {
    int b;

    public Derive(int b) {
        super();
        this.b = b;
    }

    //实现接口的抽象方法
    public void print() {
        System.out.println("In Derive!");
    }
}

//定义Derive的子类Derive1
class Derive1 extends Derive {
    int c;

    public Derive1(int b, int c) {
        super(b);
        this.c = c;
    }

    public void print() {
        System.out.println("In Derive1!");
    }
}
